
#include "appinc.h"


#ifndef HAVE_STRLCPY
size_t strlcpy(char *dest, const char *src, size_t dest_size)
{
	register char *d = dest;
	register const char *s = src;
	register size_t n = dest_size;

	/* Copy as many bytes as will fit */
	if (n != 0 && --n != 0) {
		do {
			if ((*d++ = *s++) == 0)
				break;
		} while (--n != 0);
	}

	/* Not enough room in dest, add NUL and traverse rest of src */
	if (n == 0) {
		if (dest_size != 0)
			*d = '\0'; /* NUL-terminate dest */
		while (*s++)
			;
	}

	return (s - src - 1); /* count does not include NUL */
}
#endif

int libstr_cmp_prefix(const char *s1, const char *s2)
{
	if (s1 == NULL || s2 == NULL)
		return -EINVAL;
	
	if (s1 == s2)
		return 0;
	
	return strncmp(s1, s2, strlen(s2));

}


int libstr_str_to_hex(const char *str, uint8_t *hex)
{
	int i, size, len = 0;
	uint8_t result;
	
	if (!hex || !str)
		return -EINVAL;

	size = strlen(str);
	for (i = 0; i < size; i++) {
		if (isdigit(str[i]))
			result = str[i] - '0';
		else if (islower(str[i]))
			result = str[i] - 'a' + 10;
		else if (isupper(str[i]))
			result = str[i] - 'A' + 10;
		else if (str[i] == ' ' || str[i] == '\t')
			continue;
		else
			return -1;
		if (len%2)
			hex[i/2] |= result;
		else
			hex[i/2] = (result<<4);
		len++;
	}

	return len/2;
}


int libstr_hex_to_str(uint8_t *hex, uint32_t hex_len, char *str)
{
	uint8_t tmp;
	
	if (!hex || !str || !hex_len)
		return -1;

	while (hex_len--) {
		tmp = (*hex>>4)&0xF;
		if (tmp >= 0xA)
			*str++ = tmp - 0xA + 'A';
		else
			*str++ = tmp + '0';

		tmp = *hex++ & 0xf;
		if (tmp >= 0xA)
			*str++ = tmp - 0xA + 'A';
		else
			*str++ = tmp + '0';
	}
	*str = '\0';

	return 0;
}


